<?php


namespace apps\marriage\core\service;


use apps\marriage\core\logic\FileLogic;
use apps\marriage\core\model\Adv;
use think\Exception;
use vm\com\BaseService;

class AdvService extends BaseService
{
    const TYPE_IMG = 10;    // 图片
    const TYPE_VIDEO = 20;  // 视频

    const LINK_TYPE_WEB_PAGE = 10;  // 网页链接
    const LINK_TYPE_WEAPP_PAGE = 20;  // 小程序页面

    /**
     * @inheritDoc
     * @return Adv
     */
    protected function getModel()
    {
        return new Adv();
    }

    /**
     * @return AdvPositionService
     */
    private function getAdvPositionService()
    {
        return service('AdvPosition', SERVICE_NAMESPACE);
    }

    /**
     * @return FileLogic
     */
    private function getFileLogic()
    {
        return logic('File', LOGIC_NAMESPACE);
    }

    public function deleteByPositionId($positionId)
    {
        return $this->delete([
            'position_id' => $positionId
        ]);
    }

    public function getByPk($id)
    {
        $data = parent::getByPk($id);
        if($data && $data['type'] == self::TYPE_IMG) {
            $file = $this->getFileLogic()->file($data['file_id']);
            $data['file_url'] = $file['url'];
        }
        return $data;
    }

    public function getByPosition($position)
    {
        $advPosition = $this->getAdvPositionService()->getByCode($position);
        if(empty($advPosition)) {
            throw new Exception('广告位无效');
        }
        $res = $this->getModel()->getByPositionId($advPosition['id'], 1);
        if($res) {
            foreach ($res as &$rs) {
                if($rs['type'] == self::TYPE_IMG) {
                    $file = $this->getFileLogic()->file($rs['file_id']);
                    $rs['file_url'] = $file['url'];
                }
            }
        }
        return $res;
    }

    public function getRandOneByPosition($position)
    {
        $advPosition = $this->getAdvPositionService()->getByCode($position);
        if(empty($advPosition)) {
            throw new Exception('广告位无效');
        }
        $adv = $this->getModel()->getRandOneByPositionId($advPosition['id']);
        if($adv) {
            if($adv['type'] == self::TYPE_IMG || $adv['type'] == self::TYPE_VIDEO) {
                $file = $this->getFileLogic()->file($adv['file_id']);
                $adv['file_url'] = $file['url'];
            }
        }
        return $adv;
    }
}